#include <HttpServer.hpp>
#include <exception>

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    std::cout << "start" << std::endl;
    string doc_root = "./";
    std::int32_t port = 4091;
    switch (argc)
    {
    case 3:
        doc_root = argv[2];
    case 2:
        port = std::atoi(argv[1]);
    }

    try
    {
        HttpServer server{port, doc_root};

        server.get("/hello") = [&](const HttpRequest &request, HttpResponse &response)
        {
            response.body() = "hello";
            response.result(HttpResponse::status::ok);
        };

        server.get("/login") = [&](const HttpRequest &request, HttpResponse &response)
        {
            StringMap params = request.params();
            auto name = params["name"];
            auto pwd = params["pwd"];

            if (name == "xuanqi" && pwd == "123456")
                response.body() = "OK";
            else
                response.body() = "error";
            response.result(HttpResponse::status::ok);
        };

        server.post("/login") = [&](const HttpRequest &request, HttpResponse &response)
        {
            StringMap params = request.parse_query(request.body());
            std::string name = params["name"];
            std::string pwd = params["pwd"];

            if (name == "xuanqi" && pwd == "123456")
                response.body() = "OK";
            else
                response.body() = "error";
            response.result(HttpResponse::status::ok);
        };

        auto test = [](const HttpRequest &request, HttpResponse &response)
        {
            using namespace boost::beast;
            std::cout << "----------------------------------------------------" << std::endl;
            std::cout << request << std::endl;
            std::cout << "----------------------------------------------------" << std::endl;

            StringMap cookies = request.parse_cookie(request.field(HttpRequest::Field::cookie));
            std::cout << "foot1" << ": " << cookies["foot1"] << std::endl;
            std::cout << "foot2" << ": " << cookies["foot2"] << std::endl;
            
            std::cout << HttpRequest::Field::content_type << ": " << request.field(HttpRequest::Field::content_type) << std::endl;
        
            std::cout << "----------------------------------------------------" << std::endl;
            std::cout << request.body() << std::endl;
            std::cout << "----------------------------------------------------" << std::endl;
            response.body() = "OK\r\n";
        };

        server.get("/test") = test;
        server.post("/test") = test;

        server.run();
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }

    return 0;
}
